﻿<%@ WebHandler Language="C#" Class="KindEditor.Upload" %>
using System;
using System.Collections;
using System.Web;
using System.Globalization;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace KindEditor
{
    public class Upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            int maxSize = 51200000;//最大文件大小，单位kb
            var extTable = new Hashtable();//定义允许上传的文件扩展名
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            string aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            string dirname = context.Request.QueryString["dir"];
            dirname = string.IsNullOrEmpty(dirname) ? "image" : dirname;
            if (!extTable.ContainsKey(dirname)) showError("目录名不正确。");

            var imgFile = context.Request.Files["imgFile"];
            string fileExt = Path.GetExtension(imgFile.FileName).ToLower();

            if (imgFile == null) showError("请选择文件。");

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
                showError("上传文件大小超过50M的限制。");

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirname]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirname]) + "格式。");

            var now = DateTime.Now;
            string path = "/upload/" + dirname + "/" + now.Year + "/" + now.ToString("yyyyMMdd") + "/";
            string name = now.ToString("yyyyMMddHHmmss_ffff") + fileExt;
            string dir = context.Server.MapPath(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            switch (dirname)
            {
                case "image":
                    Save(imgFile, 600, dir + name, fileExt);
                    break;
                case "flash":
                case "media":
                case "file":
                    imgFile.SaveAs(dir + name);
                    break;
            }


            string fileurl = path + name;

            var hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileurl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write("{\"error\":" + hash["error"] + ",\"url\":\"" + hash["url"] + "\"}");
            context.Response.End();
        }

        /// <summary>
        /// 保存上传图片，限定图片宽度
        /// </summary>
        /// <param name="file">上传文件</param>
        /// <param name="maxwidth">限定宽度</param>
        /// <returns></returns>
        void Save(HttpPostedFile file, int maxwidth, string filepath, string fileext)
        {

            Image img = Image.FromStream(file.InputStream);
            int newwidth = img.Width > maxwidth ? maxwidth : img.Width;
            int newheight = img.Height * newwidth / img.Width;
            Bitmap bitmap = new Bitmap(newwidth, newheight);
            Graphics g = Graphics.FromImage(bitmap);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.Clear(Color.Transparent);
            g.DrawImage(img, new Rectangle(0, 0, newwidth, newheight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
            //if (iswatermark == 1 && File.Exists(watermarkpic) && newwidth > 500 && newheight > 300)
            //{
            //    System.Drawing.Image wmimg = System.Drawing.Image.FromFile(watermarkpic);
            //    g.DrawImage(wmimg, new Rectangle(newwidth - wmimg.Width, newheight - wmimg.Height, wmimg.Width, wmimg.Height), new Rectangle(0, 0, wmimg.Width, wmimg.Height), GraphicsUnit.Pixel);
            //    g.Dispose();
            //}
            try
            {
                switch (fileext)
                {
                    case ".gif":
                        bitmap.Save(filepath, ImageFormat.Gif);
                        break;
                    case ".jpg":
                    case ".jpeg":
                        bitmap.Save(filepath, ImageFormat.Jpeg);
                        break;
                    case ".bmp":
                        bitmap.Save(filepath, ImageFormat.Bmp);
                        break;
                    case ".png":
                        bitmap.Save(filepath, ImageFormat.Png);
                        break;
                    default:
                        bitmap.Save(filepath, ImageFormat.Jpeg);
                        break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                img.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        void showError(string message)
        {
            var context = System.Web.HttpContext.Current;
            var hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write("{\"error\":" + hash["error"] + ",\"message\":\"" + hash["message"] + "\"}");
            context.Response.End();
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
